package domain;

import common.DomainException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public final class Layer {

    private String name;
    private Set<Unit> units = new HashSet<Unit>();
    private Set<Rule> rules = new HashSet<Rule>();
    private Map<String, Layer> allowedLayers = new HashMap<String, Layer>();
    private int number;

    protected Layer(String name, int number) throws DomainException {
        if (!name.equals("") && number > 0) {
            this.name = name;
            this.number = number;
        } else {
            throw new DomainException("Name cannot be empty and number must be greater than 0.");
        }
    }

    protected void addAllowedLayer(Layer layer) throws DomainException {
        if (!this.getAllowedLayers().containsValue(layer)) {
            this.allowedLayers.put(layer.getName(), layer);
        } else {
            throw new DomainException("That layer is allready defined!");
        }
    }

    protected void removeAllowedLayer(String layerName) {
        this.allowedLayers.remove(layerName);
    }

    public Map<String, Layer> getAllowedLayers() {
        return this.allowedLayers;
    }

    public String getName() {
        return this.name;
    }

    protected void setName(String name) {
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    protected void setNumber(int number) {
        this.number = number;
    }

    public Set<Unit> getUnits() {
        return this.units;
    }

    protected boolean removeRule(Rule rule) {
        if (this.rules.remove(rule)) {
            return true;
        }
        return false;
    }

    protected void setRules(Set<Rule> rules) {
        this.rules = rules;
    }

    public Set<Rule> getRules() {
        return this.rules;
    }

    protected void addUnit(Unit unit) throws DomainException {
        for (Unit u : this.units) {
            if (u.getName().equals(unit.getName()) && u.getType().equals(unit.getType())) {
                throw new DomainException("Unit already exists in this layer!");
            }
        }
        this.units.add(unit);
    }

    protected boolean removeUnit(Unit unit) {
        if (this.units.remove(unit)) {
            return true;
        }
        return false;
    }

    protected boolean removeUnitByUnitName(String unitName, String unitType) {
        for (Unit unit : this.units) {
            if (unit.getName().equals(unitName) && unit.getType().name().equals(unitType)) {
                return this.units.remove(unit);
            }
        }
        return false;
    }

    protected void setUnits(Set<Unit> units) {
        this.units = units;
    }

    @Override
    public String toString() {
        return this.getName();
    }
}
